package com.briup.ch10;

/**
 * @Author briup-adam
 * @Date 2023/10/27 下午5:19
 * @Description
 **/

public class Bum2 {
    int num;
    // 0（海鹏生产） 1（乔辉） 2（张美娜）
    int flag;
}

class Producer2 extends Thread {
    private Bum2 bum;

    Producer2(String name, Bum2 bum) {
        super(name);
        this.bum = bum;
    }

    @Override
    public void run() {
        for (int i = 1; i < 101; i++) {
            synchronized (bum) {
                while (bum.flag != 0) {
                    try {
                        bum.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("第" + i + "次，" + this.getName() + ": 开始生产包子...");
                bum.num += 2;
                System.out.println("生产完成，包子数量: " + bum.num + "，快来吃!");
                bum.flag = 1;
                bum.notifyAll();
            }
        }
    }
}
class   Customer2  extends  Thread{
    private   Bum2 bum;
    Customer2(String  name,Bum2  bum){
        super(name);
        this.bum=bum;
    }

    @Override
    public void run() {
        for (int i = 1; i <101 ; i++) {
            synchronized (bum){
                while (bum.flag!=1){
                    try {
                        bum.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("第" + i + "次，" + this.getName() + " 开始吃包子...");
                bum.num--;
                System.out.println("消费完成，包子数量: " + bum.num + "，快生产吧!");
                bum.flag = 2;
                bum.notifyAll();
            }
        }
    }
}
class   Customer3  extends  Thread{
    private   Bum2 bum;
    Customer3(String  name,Bum2  bum){
        super(name);
        this.bum=bum;
    }

    @Override
    public void run() {
        for (int i = 1; i <101 ; i++) {
            synchronized (bum){
                while (bum.flag!=2){
                    try {
                        bum.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("第" + i + "次，" + this.getName() + " 开始吃包子...");
                bum.num--;
                System.out.println("消费完成，包子数量: " + bum.num + "，快生产吧!");
                bum.flag = 0;
                bum.notifyAll();
            }
        }
    }
}

class  MoreCommunication{
    public static void main(String[] args) {
        Bum2 bum = new Bum2();
        Producer2 producer = new Producer2("海鹏包子铺", bum);
        Customer2 customer2 = new Customer2("乔辉", bum);
        Customer3 customer3 = new Customer3("张美娜", bum);
        producer.start();
        customer2.start();
        customer3.start();
    }
}
